<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="global-drawer-tabs-separate" v-loading="isLoading">
      <el-tabs v-model="tabsData.active">
        <el-tab-pane
          v-for="item in tabsData.list"
          :key="item.name"
          :label="item.label"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>

      <div class="separate-main" v-if="detailData">
        <component
          ref="componentsRef"
          :is="getComponentName"
          :detailData="detailData"
        />
      </div>
    </div>

    <template #footer>
      <template v-if="detailData?.state === '1'">
        <el-button @click="handleClickRefuse" :loading="isLoading"
          >拒绝售后</el-button
        >
        <el-button
          type="primary"
          @click="handleClickConfirm"
          :loading="isLoading"
          >同意售后</el-button
        >
      </template>
      <template v-if="detailData?.state === '3'">
        <el-button
          type="primary"
          @click="handleClickReply"
          :loading="isLoading"
          >{{
            detailData?.typeAppeal === '1' ? '补发商品' : '立即退款'
          }}</el-button
        >
      </template>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, PropType, watch, computed, markRaw, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import DetailInfo from './detail-info.vue';
import DetailGoods from './detail-goods.vue';
import DetailLogistics from './detail-logistics.vue';
import { getAppealDetail, updateAppeal } from '@/apis/appeal';

// 加载状态
const isLoading = ref(false);

// 表单 - ref
// const formRef = ref<InstanceType<typeof ElForm>>();
const componentsRef = ref<any>();

// tabs
const tabsData = reactive({
  active: '',
  list: [
    {
      label: '基本信息',
      name: 'info',
      component: markRaw(DetailInfo)
    },
    {
      label: '商品清单',
      name: 'goods',
      component: markRaw(DetailGoods)
    },
    {
      label: '物流信息',
      name: 'logistics',
      component: markRaw(DetailLogistics)
    }
  ]
});

// 初始化tabs
const initTabs = () => {
  const name = props.tabsActive || tabsData.list[0].name;
  tabsData.active = name;
};

// 详情
const detailData = ref<API.appeal.EntitySchema>();

const requestDataDetail = () => {
  isLoading.value = true;
  getAppealDetail(props.rowData.ownId!)
    .then((res) => {
      isLoading.value = false;
      detailData.value = res.data;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '50%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  // tab选中菜单
  tabsActive: {
    type: String,
    default: ''
  },

  rowData: {
    // type: Object as PropType<TempsPost>,
    type: Object as PropType<API.appeal.EntitySchema>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// computed - 动态组件
const getComponentName = computed(() => {
  const name = tabsData.active;
  const tabData = tabsData.list.find((item) => item.name === name);
  if (!tabData) return '';
  return tabData.component;
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;

    // 初始化tabs
    initTabs();

    // 从接口拿数据
    requestDataDetail();
  },
  {
    immediate: true
  }
);

// btn - 拒绝售后
const handleClickRefuse = async () => {
  // 二次确认
  try {
    await ElMessageBox.confirm('是否拒绝本次售后？', '售后操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch (error) {
    return;
  }

  // 提交订单
  submitDataUpdate({ isRefuse: true });
};

// btn - 同意售后
const handleClickConfirm = async () => {
  // 二次确认
  try {
    await ElMessageBox.confirm(
      '请核实订单信息，是否同意本次售后？',
      '售后操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
  } catch (error) {
    return;
  }

  // 提交订单
  submitDataUpdate({});
};

// btn - 处理售后
const handleClickReply = async () => {
  // 是否换货
  if (detailData.value?.typeAppeal === '1') {
    // 判断是否在发货页面，否则跳转
    if (tabsData.active !== 'logistics') {
      tabsData.active = 'logistics';
      return;
    }

    // 二次确认
    try {
      await ElMessageBox.confirm(
        '请核实订单信息，不填写发货信息则代表订单无物流发货',
        '换货售后',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
    } catch (error) {
      return;
    }

    // 获取快递数据
    const logisticsList: API.logistics.EntityDto[] =
      componentsRef.value?.getFormData() || [];

    const dataOpt: API.appeal.EntityDto = {
      logistics: logisticsList
    };

    // 提交订单
    submitDataUpdate(dataOpt);
  }

  // 是否退货退款
  if (detailData.value?.typeAppeal === '2') {
    // 二次确认
    try {
      await ElMessageBox.confirm(
        '请核实订单信息，退款后金额原路返回',
        '退货退款',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
    } catch (error) {
      return;
    }

    // 提交订单
    submitDataUpdate({});
  }
};

// submit - update
const submitDataUpdate = (dataOpt: API.appeal.EntityDto) => {
  isLoading.value = true;
  updateAppeal(props.rowData.ownId!, dataOpt)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped></style>
